"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交后基本语句功能验证，create/alter/drop index 后提交/回滚
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、兼容B库建表并插入数据
    2、开启会话1连接B库，关闭自动提交，id字段创建btree索引，等会话2查询后提交,
       禁用索引，回滚前后explain查询计划
    3、开启会话2查询索引，会话1提交后再查询，会话1禁用索引后explain查询计划
    4、autocommit=0，删除索引，提交
    5、清理环境
Expect      :
    1、成功
    2、执行成功，回滚后使用索引
    3、无索引，提交后1条索引，计划中使用索引
    4、执行成功
    5、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0030'
        self.index_name = 'i_autocommit_0030'
        self.db_name = 'db_autocommit_0030'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:兼容B库建表并插入数据;expect:成功-----'
        self.log.info(text1)
        preset_data = f"drop table if exists {self.tb_name};" \
                      f"create table {self.tb_name}(id int, num int, " \
                      f"name varchar(20) default 'male');" \
                      f"insert into {self.tb_name} select random()*10, " \
                      f"random()*3, 'XXX' from generate_series(1,5000);"
        preset_res = self.pri_sh.execut_db_sql(preset_data, '', self.db_name)
        self.log.info(preset_data)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, preset_res,
                      f"建表失败: {text1}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, preset_res,
                      f"insert失败: {text1}")

        text2 = '-----step2:开启会话1连接B库，关闭自动提交，创建btree索引，' \
                '等会话2查询后提交，禁用索引，回滚前后explain查询计划;' \
                'expect:执行成功，回滚后使用索引-----'
        self.log.info(text2)
        sql1 = f"set autocommit to off;" \
               f"drop index if exists {self.index_name};" \
               f"create index {self.index_name} on " \
               f"{self.tb_name} using btree (id);" \
               f"select pg_sleep(3); commit;" \
               f"alter index {self.index_name} unusable;" \
               f"explain select count(*) from {self.tb_name} where id=10;" \
               f"select pg_sleep(3); rollback;" \
               f"explain select count(*) from {self.tb_name} where id=10;"
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)

        text3 = '-----step3:开启会话2查询索引，会话1提交后再次查询，会话1禁用索引' \
                '后explain查询计划;expect:无索引，提交后1条索引，计划中使用索引-----'
        self.log.info(text3)
        sql2 = f"show index from {self.tb_name};" \
               f"select pg_sleep(3);" \
               f"show index from {self.tb_name};" \
               f"explain select count(*) from {self.tb_name} where id=10;"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql2, '', self.db_name))
        session2.setDaemon(True)
        # 先后启动线程，间隔1s
        session1.start()
        time.sleep(1)
        session2.start()
        session1.join(10)
        session2.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        self.assertIn('SET', result1, f"关闭自动提交失败: {text2}")
        self.assertIn(self.constant.CREATE_INDEX_SUCCESS, result1,
                      f"创建索引失败: {text2}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result1,
                      f"提交失败: {text2}")
        self.assertIn(self.constant.ALTER_INDEX_SUCCESS_MSG, result1,
                      f"修改索引失败: {text2}")
        self.assertNotIn(self.index_name, result1.split('QUERY PLAN')[1],
                         f"执行失败{text2}")
        self.assertIn(self.constant.ROLLBACK_MSG, result1, f"执行失败{text2}")
        self.assertIn(self.index_name, result1.split('QUERY PLAN')[2],
                      f"执行失败{text2}")
        self.assertEqual(result2.splitlines()[2].strip(),
                         '(0 rows)', f"执行失败{text3}")
        self.assertIn(self.index_name, result2.splitlines()[11],
                      f"执行失败{text3}")
        self.assertIn('Bitmap Index Scan', result2, f"执行失败{text3}")

        text4 = '-----step4:autocommit=0，删除索引，提交;expect:执行成功-----'
        self.log.info(text4)
        sql = f"set autocommit=0;" \
              f"drop index {self.index_name} on {self.tb_name};" \
              f"end;"
        sql_res = self.pri_sh.execut_db_sql(sql, '', self.db_name)
        self.log.info(sql_res)
        self.assertIn('SET', result1, f"关闭自动提交失败: {text3}")
        self.assertIn(self.constant.DROP_INDEX_SUCCESS_MSG, sql_res,
                      f"执行失败: {text4}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, sql_res,
                      f"执行失败: {text4}")

    def tearDown(self):
        text5 = '-----step5:清理环境 expect:成功-----'
        self.log.info(text5)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text5}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
